﻿using Atmk.WaterMeter.MIS.Entities.Enums;
using Atmk.WaterMeter.MIS.Entities.Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Serialization.Json;
using System.Threading.Tasks;

namespace Atmk.WaterMeter.MIS.Tools
{
    public static class PublicMethod
    {
        //取枚举描述
        public static string GetDescription(Enum en)
        {
            Type type = en.GetType();   //获取类型
            MemberInfo[] memberInfos = type.GetMember(en.ToString());   //获取成员
            if (memberInfos != null && memberInfos.Length > 0)
            {
                DescriptionAttribute[] attrs = memberInfos[0].GetCustomAttributes(typeof(DescriptionAttribute), false) as DescriptionAttribute[];   //获取描述特性

                if (attrs != null && attrs.Length > 0)
                {
                    return attrs[0].Description;    //返回当前描述
                }
            }
            return en.ToString();
        }

        public static List<District> getNodeNext(List<District> districts, string id, List<District> districtsOld, List<District> result_last_District)
        {

            if (districts.Any(m => m.Id.ToString() == id && m.NodeType == (int)TreeNodeType.last))
            {
                result_last_District.AddRange(districts.Where(m => m.Id.ToString() == id));
            }
            else
            {
                foreach (var item in districtsOld.Where(m => m.Parent == id))
                {
                    getNodeNext(districtsOld.Where(m => m.Parent == id).ToList(), item.Id.ToString(), districtsOld, result_last_District);
                }
            }
            return result_last_District;

        }

        /// <summary>
        /// 将C#数据实体转化为JSON数据
        /// </summary>
        /// <param name="obj">要转化的数据实体</param>
        /// <returns>JSON格式字符串</returns>
        public static string JsonSerialize<T>(T obj)
        {
            DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(T));
            MemoryStream stream = new MemoryStream();
            serializer.WriteObject(stream, obj);
            stream.Position = 0;

            StreamReader sr = new StreamReader(stream);
            string resultStr = sr.ReadToEnd();
            sr.Close();
            stream.Close();

            return resultStr;
        }

        public static int[] ToIntArray(string s, char separator)
        {
            string[] ar = s.Split(separator);
            List<int> ints = new List<int>();
            foreach (var item in ar)
            {
                int v;
                if (int.TryParse(item, out v))
                    ints.Add(v);
            }
            return ints.ToArray();
        }

    }
}
